'use strict';

import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import {
  Paper,
  Button,
  Checkbox,
  IconButton,
} from '@material-ui/core'

import DeleteIcon from '@material-ui/icons/Delete'


import Typography from '@material-ui/core/Typography'
import MUInput from '../../forms/input'
import MUSelect from '../../forms/select'
import MUAsyncSelect from '../../forms/asyncSelect'

const electron = window.require('electron')

const styles = theme => ({
  root: {
    width: window.innerWidth - 120,
    margin: 10,
    // backgroundColor: '#CCC',
    borderRadius: 0,
  },
  labels: {
    display: 'flex'
  },
  label: {
    margin: '0 2px',
    textAlign: 'center'
  },
  topcontainer: {
    display: 'flex'
  },
  price: {
    fontSize: '2em',
    color: '#A31515'
  },
  button: {
    margin: '0 2px',
    width: '120px !important',
    borderRadius: 0,
  },
});

class MedicineBlock extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      rows: 1,
    }
    props.Ref(this)
  }

  getValue(state, k) {
    if (state === 'price') {
      const price = parseFloat(this.state[`${state}_${k}`])
      if (isNaN(price)) return ''
      else return price.toFixed(2)
    }
    return this.state[`${state}_${k}`] || ''
  }

  changeHandle(state, k, item) {
    const states = this.state
    if (state === 'drug') {
      states[`${state}_${k}`] = item
      states[`doseunit_${k}`] = item.dosageunit
      states[`postfix_${k}`] = item.postfix
      states[`count_${k}`] = '1'
      states[`group_${k}`] = false
      states[`days_${k}`] = '1'
      states[`price_${k}`] = item.price
    } else if (state === 'count') {
      states[`${state}_${k}`] = item.target.value
      states[`doseunit_${k}`] = item.dosageunit
      states[`price_${k}`] = parseInt(item.target.value) * parseFloat(this.getValue('drug', k).price)
    } else if (state === 'group') {
        states[`group_${k}`] = item.target.checked
    } else if (state === 'times') {
        states[`${state}_${k}`] = item
    } else if (state === 'usage') {
        states[`${state}_${k}`] = item
    } else {
        states[`${state}_${k}`] = item.target.value
    }
    this.setState(states)
    this.hangleMedicinesChanged(states)
  }

  removeAllRowHandle() {
    const states = this.init()
    this.hangleMedicinesChanged(states)
  }

  init() {
    const states = {
      'rows': 1,
    }
    const keys = [
      'drug',
      'dose',
      'doseunit',
      'usage',
      'times',
      'days',
      'count',
      'postfix',
      'price',
      'comment'
    ]
    for (let k = 0; k < 20; k += 1) {
      for (let j = 0; j < keys.length; j += 1) {
        states[`${keys[j]}_${k}`] = ''
      }
    }
    this.setState(states)
    return states
  }

  removeRowHandle(k) {
    const { rows } = this.state
    let states = {
      rows: rows - 1
    }
    if (rows == 1) {
      states = {
        'drug_0': '',
        'dose_0': '',
        'doseunit_0': '',
        'days_0': '',
        'count_0': '',
        'postfix_0': '',
        'price_0': '',
        'comment_0': ''
      }
      this.setState(states)
      this.hangleMedicinesChanged(states)
      return
    }
    const keys = [
      'drug',
      'dose',
      'doseunit',
      'usage',
      'times',
      'days',
      'count',
      'postfix',
      'price',
      'comment'
    ]
    for (let m = 0; m < rows; m += 1) {
      for (let j = 0; j < keys.length; j += 1) {
        if (m < k) {
          states[`${keys[j]}_${m}`] = this.state[`${keys[j]}_${m}`]
        } else if (m < rows - 1) {
          states[`${keys[j]}_${m}`] = this.state[`${keys[j]}_${m + 1}`]
        } else {
          states[`${keys[j]}_${m}`] = ''
        }
      }
    }
    this.setState(states)
    this.hangleMedicinesChanged(states)
  }

  fetch(_id) {
    let state = electron.ipcRenderer.sendSync('getPatient', _id)
    if (state && state.medicines !== undefined) {
      const { medicines } = state
      if (medicines[`drugs_${medicines.rows - 1}`] !== '') {
        medicines.rows += 1
      }
      this.setState(medicines)
      setTimeout(() => this.forceUpdate(), 200)
    }
  }

  componentDidMount() {
    this.fetch(this.props._id)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps._id !== undefined) {
      this.init()
      this.fetch(nextProps._id)
    }
  }

  hangleMedicinesChanged(states) {
    electron.ipcRenderer.send('patient', {
      _id: this.props._id,
      medicines: states
    })
  }

  save() {
    electron.ipcRenderer.send('save', {
      _id: this.props._id,
      type: 'medicines'
    })
  }
  
  render() {
    const { classes } = this.props
    const rows = []
    let total = 0
    for (let k = 0; k < this.state.rows; k += 1) {
      let t = parseFloat(this.state[`price_${k}`])
      if (isNaN(t) === false) total += parseFloat(this.state[`price_${k}`])
      rows.push(
        <div key={`row-${k}`}>
          <Checkbox
            checked={this.getValue('group', k)}
            onChange={(item) => this.changeHandle('group', k, item)}
          />
          <MUAsyncSelect
            required
            dense
            label=''
            url='api/drugs/pharmacy'
            width={380}
            defaultValue={this.getValue('drug', k)}
            value={this.getValue('drug', k)}
            onChange={(item) => this.changeHandle('drug', k, item)}
          />
          <MUInput
            required
            dense
            postfix={this.getValue('doseunit', k)}
            label=''
            width={120}
            value={this.getValue('dose', k)}
            onChange={(item) => this.changeHandle('dose', k, item)}
          />
          <MUSelect
            required
            dense
            label=''
            width={120}
            defaultValue={this.getValue('usage', k)}
            value={this.getValue('usage', k)}
            onChange={(item) => this.changeHandle('usage', k, item)}
            options={[
              { value: '口服', label: '口服' },
              { value: '静脉输液', label: '静脉输液' },
              { value: '续静滴', label: '续静滴' },
              { value: '皮试', label: '皮试' },
              { value: '肌肉注射', label: '肌肉注射' },
              { value: '雾化吸入', label: '雾化吸入' },
              { value: '入壶', label: '入壶' },
              { value: '含服', label: '含服' },
              { value: '外用', label: '外用' },
            ]}
          />
          <MUSelect
            required
            dense
            label=''
            width={120}
            row={k}
            defaultValue={this.getValue('times', k)}
            value={this.getValue('times', k)}
            onChange={(item) => this.changeHandle('times', k, item)}
            options={[
              { value: '一日一次', label: '一日一次' },
              { value: '一日两次', label: '一日两次' },
              { value: '一日三次', label: '一日三次' },
              { value: '立即执行', label: '立即执行' },
              { value: '隔日执行', label: '隔日执行' },
            ]}
          />
          <MUInput
            required
            dense
            label=''
            width={80}
            postfix="天"
            value={this.getValue('days', k)}
            onChange={(item) => this.changeHandle('days', k, item)}
          />
          <MUInput
            required
            dense
            label=''
            width={80}
            postfix={this.getValue('postfix', k)}
            value={this.getValue('count', k)}
            onChange={(item) => this.changeHandle('count', k, item)}
          />
          <MUInput
            dense
            readOnly
            label=''
            width={100}
            value={this.getValue('price', k)}
          />
          <MUInput
            dense
            label=''
            width={120}
            skip={2}
            value={this.getValue('comment', k)}
            onChange={(item) => this.changeHandle('comment', k, item)}
            onSubmit={() => {
              const state = {
                rows: this.state.rows + 1,
                [`times_${this.state.rows}`]: this.state[`times_${this.state.rows - 1}`],
                [`usage_${this.state.rows}`]: this.state[`usage_${this.state.rows - 1}`],
              }
              this.setState(state)
            }}
          />
          <IconButton aria-label="Delete" onClick={() => this.removeRowHandle(k)}>
            <DeleteIcon fontSize="small" />
          </IconButton>
        </div>
      )
    }
    return (
      <form className={classes.root}>
        <div className={classes.topcontainer}>
          <Button
            className={classes.button}
            variant="raised"
            color="primary"
            size="medium"
            style={{marginRight: 16}}
            onClick={() => this.save()}
          >
            保存
          </Button>
          <Button
            className={classes.button}
            variant="raised"
            color="secondary"
            size="medium"
            style={{marginRight: 16}}
            onClick={() => this.removeAllRowHandle()}
          >
            清空
          </Button>
          <div className={classes.price}>
            ¥{total.toFixed(2)}
          </div>
        </div>
        <div className={classes.labels}>
          <Typography className={classes.label} style={{ width: 40}}>分组</Typography>
          <Typography className={classes.label} style={{ width: 380}}>处方内容</Typography>
          <Typography className={classes.label} style={{ width: 120}}>剂量</Typography>
          <Typography className={classes.label} style={{ width: 120}}>用药方式</Typography>
          <Typography className={classes.label} style={{ width: 120}}>次数</Typography>
          <Typography className={classes.label} style={{ width: 80}}>天数</Typography>
          <Typography className={classes.label} style={{ width: 80}}>数量</Typography>
          <Typography className={classes.label} style={{ width: 100}}>小计</Typography>
          <Typography className={classes.label} style={{ width: 120}}>嘱托</Typography>
        </div>
        {rows}
      </form>
    )
  }
}

MedicineBlock.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(MedicineBlock);